﻿
namespace SistemaLogistica.Windows.Forms.Almacen.Operaciones
{
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Windows.Forms;
    using EDOSwit.Controls.DataGridView;
    using EDOSwit.Controls.EventArgs;
    using EDOSwit.Controls.Helpers;
    using EDOSwit.Controls.Types;
    using EDOSwit.Controls.UserControls;
    using SistemaLogistica.Business.Entities;
    using SistemaLogistica.Business.Logic;
    using SistemaLogistica.Windows.Helpers;

    public partial class CwfNotaSalida : MaestroDetalleSeguro, IRefrescar
    {
        public CwfNotaSalida()
        {
            InitializeComponent();
            this.dgvDetalle.DataGridView.KeyDown += new KeyEventHandler(DataGridView_KeyDown);
        }

        private void DataGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (this.dgvDetalle.DataGridView.CurrentCell != null)
                {
                    if (Mensaje.ShowMessageConfirm(this.ParentForm, Constantes.TituloMensaje, "¿Desea eliminar el Detalle?") == DialogResult.No)
                    {
                        e.Handled = true;
                    }
                    else
                    {
                        this.dgvDetalle.DataGridView.Rows.Remove(this.dgvDetalle.DataGridView.CurrentRow);
                        if (this.dgvDetalle.DataGridView.Rows.Count == 0)
                        {
                            this.dgvDetalle.DataGridView.Rows.Add();
                        }
                    }
                }
            }
        }

        protected override void LoadPermisos()
        {
            this.TsMenu.Permisos.AddRange(Metodos.GetPermisos(Convert.ToByte(this.Tag)));
        }

        protected override void InitialLoad()
        {
            try
            {
                lblUsuario.Text = Empresa.Usuario.Nombre;
                lblUsuario.Tag = Empresa.Usuario.IdEmpleado;

                this.cmbNumero.DisplayMember = "IdOrdenPedido";
                this.cmbNumero.ValueMember = "IdOrdenPedido";

                this.MaestroBindingSource.DataSource = NotaSalidaManager.Instancia.Listar();
                this.dgvMaestro.DataSource = this.MaestroBindingSource;
                LoadDataGridView();
                OcultarColumnas();
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, Constantes.TituloMensaje, ex.Message);
            }
        }

        protected override void FocusKeyPress(object sender, KeyPressEventArgs e)
        {
            base.FocusKeyPress(sender, e);
        }

        private void OcultarColumnas()
        {
            this.dgvMaestro.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.dgvMaestro.Columns["OrdenPedido"].Visible = false;
            this.dgvMaestro.Columns["Descripcion"].Visible = false;
            this.dgvMaestro.Columns["Empleados"].Visible = false;
            this.dgvMaestro.Columns["IdNotaSalida"].HeaderText = "NotaSalida";
        }

        private void LoadDataGridView()
        {
            this.dgvDetalle.DataGridView.Rows.Clear();
            this.dgvDetalle.DataGridView.Columns.Clear();
            this.dgvDetalle.Mode = Mode.ReadOnly;

            CustomColumnDataGridView colummn = new CustomColumnDataGridView();
            colummn.Name = "Bien";
            colummn.HeaderText = "Bien";
            colummn.Width = 300;
            colummn.ControlType = CustomControlType.FindDropDownList;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);
            colummn.ColumnNext = 2;

            colummn = new CustomColumnDataGridView();
            colummn.Name = "UnidadMedida";
            colummn.HeaderText = "UnidadMedida";
            colummn.ControlType = CustomControlType.TextBox;
            colummn.ReadOnly = true;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            colummn = new CustomColumnDataGridView();
            colummn.Name = "Cantidad";
            colummn.HeaderText = "Cantidad";
            colummn.Width = 80;
            colummn.ControlType = CustomControlType.TextBox;
            colummn.DataType = DataType.Decimales;
            this.dgvDetalle.CustomColumns.AddColumn(colummn);

            this.dgvDetalle.DataGridView.Rows.Add();
            this.dgvDetalle.DataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        protected override void CellPainting(ref DataGridViewCellPaintingEventArgs e)
        {
            Graphics g = e.Graphics;
            bool selected = ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected);
            Color fcolor = (selected ? e.CellStyle.SelectionForeColor : e.CellStyle.ForeColor);
            Color bcolor = (selected ? e.CellStyle.SelectionBackColor : e.CellStyle.BackColor);
            Font font = e.CellStyle.Font;
            font = new Font("Tahoma", 7);

            NotaSalida notaSalida = this.MaestroBindingSource[e.RowIndex] as NotaSalida;

            if (notaSalida != null)
            {
                int x = e.CellBounds.Left + e.CellStyle.Padding.Left;
                int y = e.CellBounds.Top + e.CellStyle.Padding.Top;
                int width = e.CellBounds.Width - (e.CellStyle.Padding.Left + e.CellStyle.Padding.Right);
                int height = 13 + (e.CellStyle.Padding.Top + e.CellStyle.Padding.Bottom);

                g.FillRectangle(new SolidBrush(bcolor), e.CellBounds);
                y = y + height - 1;

                if (e.ColumnIndex == 0)
                {
                    font = new Font("Tahoma", 8, FontStyle.Bold);

                    if (selected)
                        TextRenderer.DrawText(e.Graphics, "Nº: " + notaSalida.IdNotaSalida.ToString().PadLeft(7, '0'), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                    else
                        TextRenderer.DrawText(e.Graphics, "Nº: " + notaSalida.IdNotaSalida.ToString().PadLeft(7, '0'), font, new Rectangle(x, y, width, height), System.Drawing.Color.Blue, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);

                    font = new Font("Tahoma", 7);
                    y = y + height - 1;

                    TextRenderer.DrawText(e.Graphics, "P: " + (notaSalida.OrdenPedido.Pedido.Area ?? new Area()).Nombre ?? string.Empty, font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                }
                else
                {
                    font = new Font("Tahoma", 9, FontStyle.Bold);

                    if (selected)
                        TextRenderer.DrawText(e.Graphics, "F: " + notaSalida.Fecha.ToShortDateString() , font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                    else
                        TextRenderer.DrawText(e.Graphics, "F: " + notaSalida.Fecha.ToShortDateString() , font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);

                    font = new Font("Tahoma", 7);
                    y = y + height - 1;
                }
            }
        }

        protected override void EventoNuevo()
        {
            this.cmbNumero.SelectedIndex = -1;
            this.dtFecha.Enabled = false;
            this.dtFecha.Value = EmpresaManager.Instancia.Fecha();
            this.dtFecha.Focus();
        }

        protected override void EventoEditar()
        {
            this.dtFecha.Enabled = true;
            this.dtFecha.Focus();
        }

        protected override void EventoGuardar()
        {
            this.dgvDetalle.Mode = Mode.ReadOnly;
        }

        protected override void EventoCancelar()
        {
            this.dgvDetalle.Mode = Mode.ReadOnly;
        }

        protected override void LoadData(object obj)
        {
            NotaSalida notaSalida = obj as NotaSalida;
            if (notaSalida != null)
            {
                this.identificador = notaSalida.IdNotaSalida;
                this.dtFecha.Value = notaSalida.Fecha;
                this.cmbNumero.Text = notaSalida.OrdenPedido.IdOrdenPedido.ToString();
                this.cmbArea.SelectedValue =notaSalida.OrdenPedido.Pedido.Area.IdArea;
                this.ucUbigeo.cmbDepartamento.SelectedValue = notaSalida.OrdenPedido.Pedido.Area.Sucursal.Ubigeo.IdDepartamento;
                this.ucUbigeo.cmbProvincia.SelectedValue = notaSalida.OrdenPedido.Pedido.Area.Sucursal.Ubigeo.IdProvincia;
                this.ucUbigeo.cmbDistrito.SelectedValue = notaSalida.OrdenPedido.Pedido.Area.Sucursal.Ubigeo.IdDistrito;
                this.ucUbigeo.cmbSucursal.SelectedValue = notaSalida.OrdenPedido.Pedido.Area.Sucursal.IdSucursal;
                this.cmbArea.SetText(notaSalida.OrdenPedido.Pedido.Area.IdArea.ToString());
                this.txtDescripcion.Text = notaSalida.Descripcion;
                this.lblUsuario.Text = notaSalida.Empleados.Nombre;
                this.lblUsuario.Tag = notaSalida.Empleados.IdEmpleado;
                int index = 0;
                this.dgvDetalle.DataGridView.Rows.Clear();
                foreach (DetalleNotaSalida d in notaSalida.Detalle)
                {
                    index = this.dgvDetalle.DataGridView.Rows.Add(1);
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Value = d.Bien.Nombre;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[0].Tag = d.Bien.IdBien;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[1].Value = d.Bien.UnidadMedidia.Abreviatura;
                    this.dgvDetalle.DataGridView.Rows[index].Cells[2].Value = d.Cantidad;
                }
                this.dgvDetalle.DataGridView.Rows.Add();
            }
        }

        protected override bool SaveData()
        {
            bool result = false;
            int posicion = this.MaestroBindingSource.Position;

            try
            {
                switch (this.estadoActual)
                {
                    case EstadoActual.Nuevo:
                        NotaSalidaManager.Instancia.Registrar(GetNotaSalida());
                        break;
                    case EstadoActual.Editar:
                        NotaSalidaManager.Instancia.EditarNotaSalida(GetNotaSalida());
                        break;
                    case EstadoActual.Eliminar:
                        NotaSalidaManager.Instancia.Eliminar(Convert.ToInt32(this.identificador));
                        this.MaestroBindingSource.RemoveCurrent();
                        posicion -= 1;
                        break;
                }
                result = true;
                InitialLoad();
                this.MaestroBindingSource.Position = posicion;
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, Constantes.TituloMensaje, ex.Message);
            }
            return result;
        }

        private NotaSalida GetNotaSalida()
        {
            NotaSalida notaSalida = new NotaSalida
            {
                IdNotaSalida = Convert.ToInt32(this.identificador),
                Fecha = this.dtFecha.Value,
                Empleados = new Empleados { IdEmpleado = Empresa.Usuario.IdEmpleado },
                OrdenPedido = new OrdenPedido { IdOrdenPedido = Convert.ToInt32(this.cmbNumero.Tag) },
                Descripcion = this.txtDescripcion.Text,
                Detalle = new List<DetalleNotaSalida>()
            };
            foreach (DataGridViewRow row in this.dgvDetalle.DataGridView.Rows)
            {
                if (ValidateData(row.Index))
                {
                    notaSalida.Detalle.Add(new DetalleNotaSalida
                    {
                        Bien = new Bien { IdBien = Convert.ToInt32(row.Cells[0].Tag) },
                        Cantidad = Convert.ToDecimal(row.Cells[2].Value),
                    });
                }
            }
            return notaSalida;
        }

        private bool ValidateData(int rowIndex)
        {
            bool result = true;

            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[0].Tag == null)
            {
                result = false;
            }
            if (this.dgvDetalle.DataGridView.Rows[rowIndex].Cells[2].Value == null)
            {
                result = false;
            }
            
            return result;
        }

        protected override bool ValidateData()
        {
            bool result = true;

            if (this.cmbNumero.SelectedIndex == -1)
            {
                this.errValidator.SetError(this.cmbNumero, "Seleccionar Numero.");
                result = false;
            }
            else
            {
                this.errValidator.SetError(this.cmbNumero, string.Empty);
            }
            int contador1 = 0;
            int contador2 = 0;
            foreach (DataGridViewRow row in dgvDetalle.DataGridView.Rows)
            {
                if (row.Cells[0].Tag == null) continue;
                if (ValidateData(row.Index)) contador1++;
                else contador2++;
            }
            if (!(contador1 != 0 && contador2 == 0 && dgvDetalle.DataGridView.Rows.Count > 0))
            {
                Mensaje.ShowMessageAlert(this.ParentForm, Constantes.TituloMensaje, "Debe existir proudctos e ingresados correctamente.");
                result = false;
            }
            return result;
        }

        protected override void ClearControls()
        {
            this.identificador = 0;
            this.cmbArea.Tag = 0;
            this.cmbArea.TreeView.Nodes.Clear();
            this.cmbNumero.Text = string.Empty;
            LoadDataGridView();
            base.ClearControls();
        }

        private void cmbNumero_SelectionChangeCommitted(object sender, EventArgs e)
        {
            cmbNumero.Tag = Convert.ToInt32(cmbNumero.Text);
        }

        private void dgvDetalle_BeforeShowControl(object sender, BeforeShowControlEventArg e)
        {
            switch (e.Cell.ColumnIndex)
            {
                case 0: // Cargar Bien
                    try
                    {
                        ComboBox cmbA = e.Control as ComboBox;
                        cmbA.DataSource = null;
                        cmbA.DisplayMember = "Nombre";
                        cmbA.ValueMember = "IdBien";
                        cmbA.DataSource = BienManager.Instancia.Listar();
                    }
                    catch (Exception ex)
                    {
                        Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
                    }
                    break;
                default:
                    break;
            }
        }

        private void dgvDetalle_EnterKeyPress(object sender, EnterKeyPressEventArg e)
        {
            switch (e.ColumnIndex)
            {
                case 0: // Vehiculo
                    if (!string.IsNullOrEmpty(e.Text))
                    {
                        List<Bien> bien = BienManager.Instancia.Buscar(e.Text);
                        if (bien != null)
                        {
                            this.dgvDetalle.DataGridView.Rows[e.RowIndex].Cells[1].Value = bien[0].UnidadMedidia.Abreviatura;
                        }
                        else
                        {
                            e.Handle = false;
                        }
                    }
                    else
                    {
                        e.Handle = false;
                    }
                    break;
         
                case 2: 
                    if (string.IsNullOrEmpty(e.Text))
                    {
                        e.Handle = false;
                    }
                    else if (Convert.ToDecimal(e.Text) <= 0)
                    {
                        e.Handle = false;
                    }
                    if (e.Handle)
                    {
                        if (this.dgvDetalle.DataGridView.Rows[e.RowIndex].Cells[0].Tag != null)
                        {
                            int count = this.dgvDetalle.DataGridView.Rows.Count;
                            if (this.dgvDetalle.DataGridView.Rows[count - 1].Cells[0].Value != null)
                            {
                                if (Mensaje.ShowMessageConfirm(this.ParentForm, Constantes.TituloMensaje, "¿Desea agregar un nuevo Detalle?") == DialogResult.Yes)
                                {
                                    this.dgvDetalle.DataGridView.Rows.Add();
                                }
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        private void ucUbigeo_seleccionarSucursal(object sender, int idSucursal)
        {
            this.cmbNumero.Text = string.Empty;
            this.cmbNumero.DataSource = new List<OrdenPedido>();
            this.cmbArea.Text = string.Empty;
            Metodos.GetAreas(idSucursal, this.cmbArea.TreeView);
        }

        private void cmbArea_SelectedNode(object sender, EventArgs e)
        {
            this.cmbNumero.Text = string.Empty;
            this.cmbNumero.DataSource = new List<OrdenPedido>();

            if (this.cmbArea.Tag != null)
            {    
                this.cmbNumero.DataSource = OrdenPedidoManager.Instancia.ListarPorArea(Convert.ToInt32(this.cmbArea.Tag), true);
            }
        }

        private void btnBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                this.MaestroBindingSource.DataSource = NotaSalidaManager.Instancia.Buscar(this.dtpDesde.Value, this.dtpHasta.Value);
                this.dgvMaestro.DataSource = this.MaestroBindingSource;
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
            }
        }

        #region Miembros de IRefrescar

        public void Refrescar()
        {
            InitialLoad();
        }

        #endregion
    }
}
